package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Override
    public PageResult findAll(Integer page, Integer pagesize) {
        //1、分页查询数据列表
        Query query = new Query().limit(pagesize)
                .skip((page-1) * pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);
        //2、查询总记录数
        long count = mongoTemplate.count(query, Video.class);
        //3、构造返回值
        return new PageResult(page,pagesize,(int) count, list);
    }

    //保存视频数据
    public void save(Video video) {
        video.setId(ObjectId.get());
        video.setCreated(System.currentTimeMillis());
        video.setVid(idService.getNextId("video"));
        mongoTemplate.save(video);
    }

    @Override
    public void followUser(FollowUser user) {
        user.setId(ObjectId.get());
        user.setCreated(System.currentTimeMillis());
        mongoTemplate.save(user);
    }

    //调用API根据用户id和关注用户id
    public void disFollowUser(Long userId, Long followUserId) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId)
        );
        mongoTemplate.remove(query, FollowUser.class);
    }

    @Override
    public PageResult findAll(int page, int pagesize, Long uid) {
        //1、分页查询数据列表
        Criteria criteria = new Criteria();
        if(uid != null) {
            criteria = criteria.where("userId").is(uid);
        }
        Query query = new Query(criteria).limit(pagesize)
                .skip((page-1) * pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);
        //2、查询总记录数
        long count = mongoTemplate.count(query, Video.class);
        //3、构造返回值
        return new PageResult(page,pagesize,(int) count, list);
    }

    @Override
    public Video findById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }
}
